//
//  HomeTableViewCell.m
//  FD
//
//  Created by xiaofang wang on 2018/12/7.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  嵌套一个collectionView

#import "HomeGoodsDetailTableViewCell.h"
#import "HomeGoodsDetailSectionView2.h" //section
#import "HomGoodsSingleCell.h" //item

//model
#import "HomeGoodsDetailBigModel.h" //大
#import "HomeGoodsDetailModel.h" //小


@interface HomeGoodsDetailTableViewCell()<UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
/**1.collectionView 动态计算高度*/
@property (nonatomic, strong) UICollectionView *collectionView;
/**2.配料数据源*/
@property (nonatomic, strong) NSArray *ingredientClassifyListArr;
/**12-5主食的价格,默认需要加上 点击加料的时候需要用到 */
@property (nonatomic, strong) NSNumber *stapleFoodPrice;
@end

@implementation HomeGoodsDetailTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {

    [self.contentView addSubview:self.collectionView];
}

- (void)layoutSubviews {
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.with.bottom.with.left.with.right.mas_equalTo(self.contentView);
        make.height.mas_equalTo(@100).priorityLow();
    }];
}

#pragma mark - getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        
        //禁止滚动🚫
        _collectionView.scrollEnabled = NO;
        
        //设置背景
        _collectionView.backgroundColor = [UIColor whiteColor];
        //设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        //注册section
        [_collectionView registerClass:[HomeGoodsDetailSectionView2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeGoodsDetailSectionView2"];
        
        //注册cell
        [_collectionView registerClass:[HomGoodsSingleCell class] forCellWithReuseIdentifier:@"HomGoodsSingleCell"];
    }
    
    return _collectionView;
}

#pragma mark - 代理 UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.ingredientClassifyListArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    HomeGoodsDetailBigModel *bigM = self.ingredientClassifyListArr[section];
    
    return bigM.ingredientList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    HomGoodsSingleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomGoodsSingleCell" forIndexPath:indexPath];
    
    //设置数据
    HomeGoodsDetailBigModel *bigM = self.ingredientClassifyListArr[indexPath.section];
    HomeGoodsDetailModel *detailM = bigM.ingredientList[indexPath.row];
    cell.model = detailM;
    
    return cell;
}

#pragma mark - 代理 UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat w = (SCREEN_WIDTH - 10)* 0.5;
    return CGSizeMake(w, 20*2); //12-5
}

//2019-2-13取消collectionview两行之间的间距✅
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        HomeGoodsDetailSectionView2 *sectionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeGoodsDetailSectionView2" forIndexPath:indexPath];
        
        //赋值
//sectionView.titleLb.text = [NSString stringWithFormat:@"%ld",indexPath.section];
        HomeGoodsDetailBigModel *bigM = self.ingredientClassifyListArr[indexPath.section];
        sectionView.titleLb.text = bigM.name;
        
        return sectionView;
    }else {
        return nil;
    }
}


//点击cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //页面效果+计算金额
    //取出大modle
    HomeGoodsDetailBigModel *bigM =  self.ingredientClassifyListArr[indexPath.section];
    
    //取出对应的小model
    HomeGoodsDetailModel *currentDetailModel = bigM.ingredientList[indexPath.row];
    
    //判断是单选还是多选
    if ([bigM.only isEqualToNumber:@(1)]) { //单选
        //排他思想 :只要一个能被选中
        for (HomeGoodsDetailModel *innerDetailM in bigM.ingredientList) {
            innerDetailM.tagId = @(-1); //2019-2-25点了之后就修改默认值的状态。
            //不然会导致单选的情况下回同时出现两个按钮被选中价格计算也不对。✅
            //innerDetailM.defaultSelect = @(-1); //2019-2-25 使用该字段是会有问题❌
            innerDetailM.isSelected = NO; //2019-2-26 排他思想
        }
        currentDetailModel.isSelected = YES; //当前的选中
    }else { //多选
        //取反,点一次选中再点一次取消选中
        currentDetailModel.isSelected = !currentDetailModel.isSelected;
    }
    
  
    
    //中不溜子。
    //单选🔘的怎么处理
    //判断他是不单选🔘
    if (![currentDetailModel.only isEqualToNumber:@1]) { //可以多选的
        //点一次存 在点一次删除
        if (currentDetailModel.isSelected) { //存
            [bigM.selectArrayM addObject:currentDetailModel];
        }else { //删
            [bigM.selectArrayM removeObject:currentDetailModel];
        }
    }

    FDLog(@"section:%ld--row:%ld 数量:%ld",(long)indexPath.section,(long)indexPath.row,bigM.selectArrayM.count);
    
    //计算总价 & 回调结果
    [self countingSumPriceWithArr:self.ingredientClassifyListArr];

    //更新collectionView 页面
    [self.collectionView reloadData];
}

#pragma mark - 代理 UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(300, 40);
}

#pragma mark - 设置数据源 并刷新
- (void)hgdtcellReloaddataWithIngredientClassifyListArr:(NSArray *)ingredientClassifyListArr {

    FDLog(@"数据源个数是:%lu",(unsigned long)ingredientClassifyListArr.count);
    //外面把数据传递进来
    self.ingredientClassifyListArr = ingredientClassifyListArr;
    
    //刷新表格
    [self.collectionView reloadData];
}

#pragma mark - 业务逻辑
#pragma mark - 11-29计算原价、现价
/**计算商品金额*/
/**需求
 1.默认有一个金额
 
 2.选中的不同的配料计算不同的价格
 
 3.上面和下面的同时更换钱数
 
 4.2019-2-25 默认值问题。单选问题
 */

//!!!!:一计算原价 现价
//originalPrice
//currentPrice
/**计算i现价总和, 现价总和*/

- (void)countingSumPriceWithArr:(NSArray *)arr{
    
    //OC中带 * 的应该都是引用类型，可以通过指针(地址直接修改数据源的值) like NSError 的常见使用方式 请面在加一个&
    //2019-2-25 考虑默认值问题.偷懒了直接在原有逻辑上修改，能少改就少改
    [self signHaveDefaultValueToSelectWithArr:arr];  //这里修改默认值的选中状态，不需要用一个数组接收
    
//    FDLog(@"%@",arr); //这个时候数组中的内容已经反生了变化。
    
    
    //HomeGoodsDetailBigModel
    //遍历大字典的小字典,  HomeGoodsDetailModel  isSelected = YES .累加和
    __block CGFloat scp = 0;
    __block CGFloat sop = 0;
    
    [arr enumerateObjectsUsingBlock:^(HomeGoodsDetailBigModel  * _Nonnull  bigModel, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSArray *ingredientList = bigModel.ingredientList;
        
        //一:只算单选的🔘的  怎么简单怎么来
        [ingredientList enumerateObjectsUsingBlock:^(HomeGoodsDetailModel  *_Nonnull detailM, NSUInteger idx, BOOL * _Nonnull stop) {
            //only=1 && 选中 && 前几个是免费的(idx >= freeIndex)
            if ([detailM.only isEqualToNumber:@1] && detailM.isSelected) {
                //累加和
                scp += [detailM.currentPrice floatValue];
                sop += [detailM.originalPrice floatValue];
            }
        }];
        
        
        //二:计算多选点的。选中的前n个是免费的。
        NSInteger freeIndex = [bigModel.free integerValue];
        NSArray *selectArr = [bigModel.selectArrayM copy];
        [selectArr enumerateObjectsUsingBlock:^(HomeGoodsDetailModel  *_Nonnull detailM2, NSUInteger idx, BOOL * _Nonnull stop) {
            //多选: ![detailM2.only isEqualToNumber:@(1)]
            //选中的前n个是免费的: (idx >= freeIndex)
            if (![detailM2.only isEqualToNumber:@(1)] && (idx >= freeIndex)) {
                scp += [detailM2.currentPrice floatValue];
                sop += [detailM2.originalPrice floatValue];
            }
        }];
    }];
    
    
    //三:更新表头模型的原价和现价
    CGFloat sumPrice = scp + [self.stapleFoodPrice floatValue];
    //    sumPrice += 12;
    FDLog(@"现在总价:%f",sumPrice);
    
    //四:触发回调
    if ([self.delegate respondsToSelector:@selector(didCalculateIngredientTotalPrice:)]) {
        [self.delegate didCalculateIngredientTotalPrice:sumPrice];
    }
}


//2019-2-25 新加逻辑:标记有默认值的model状态为选中状态
//新知:OC中带*的都是指针,所以应该是引用类型。这里修改其中某一个array[i]的值,会导致整个数据源的具体内容的
- (void)signHaveDefaultValueToSelectWithArr:(NSArray *)array {

    for (HomeGoodsDetailBigModel *bigModel in array) {
        
        if ([bigModel.only isEqualToNumber:@(1)]) { //2019-2-25 后台说只考虑单选的情况
            
            for (HomeGoodsDetailModel *detailModel in bigModel.ingredientList) {
                if ([bigModel.defaultSelect isEqualToNumber:detailModel.tagId]) {
                    FDLog(@"1111111111111");
                    detailModel.isSelected = YES; //有默认值的默认标记选中
                    //2019-2-25 不然会导致莫名奇妙的bug
                }
            }
        }
    }
}

//12-21修改, 新增字段 free ❌这个存在问题:默认值没有考虑进去
//- (void)countingSumPriceWithArr:(NSArray *)arr{
//
//
//    //HomeGoodsDetailBigModel
//    //遍历大字典的小字典,  HomeGoodsDetailModel  isSelected = YES .累加和
//    __block CGFloat scp = 0;
//    __block CGFloat sop = 0;
//
//    [arr enumerateObjectsUsingBlock:^(HomeGoodsDetailBigModel  * _Nonnull  bigModel, NSUInteger idx, BOOL * _Nonnull stop) {
//
//        NSArray *ingredientList = bigModel.ingredientList;
//
//        //一:只算单选的🔘的  怎么简单怎么来
//        [ingredientList enumerateObjectsUsingBlock:^(HomeGoodsDetailModel  *_Nonnull detailM, NSUInteger idx, BOOL * _Nonnull stop) {
//            //only=1 && 选中 && 前几个是免费的(idx >= freeIndex)
//            if ([detailM.only isEqualToNumber:@1] && detailM.isSelected) {
//                //累加和
//                scp += [detailM.currentPrice floatValue];
//                sop += [detailM.originalPrice floatValue];
//            }
//        }];
//
//
//        //二:计算多选点的。选中的前n个是免费的。
//        NSInteger freeIndex = [bigModel.free integerValue];
//        NSArray *selectArr = [bigModel.selectArrayM copy];
//        [selectArr enumerateObjectsUsingBlock:^(HomeGoodsDetailModel  *_Nonnull detailM2, NSUInteger idx, BOOL * _Nonnull stop) {
//            //多选: ![detailM2.only isEqualToNumber:@(1)]
//            //选中的前n个是免费的: (idx >= freeIndex)
//            if (![detailM2.only isEqualToNumber:@(1)] && (idx >= freeIndex)) {
//                scp += [detailM2.currentPrice floatValue];
//                sop += [detailM2.originalPrice floatValue];
//            }
//        }];
//    }];
//
//
//    //三:更新表头模型的原价和现价
//    CGFloat sumPrice = scp + [self.stapleFoodPrice floatValue];
////    sumPrice += 12;
//    FDLog(@"现在总价:%f",sumPrice);
//
//    //四:触发回调
//    if ([self.delegate respondsToSelector:@selector(didCalculateIngredientTotalPrice:)]) {
//        [self.delegate didCalculateIngredientTotalPrice:sumPrice];
//    }
//}
@end
